package y2015.date0915pm.服务端;

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ChatServer {
    @Test
    public void main() throws Exception {

        //通过工厂获取端口号
        FactoryPort factoryPort = new FactoryPort();
        int port = factoryPort.getPortIntance();

        String host = "127.0.0.1";
        ServerSocket ss = null;

        //创建服务器对象
        try {
            //获取端口号，并依此返回
            ss = new ServerSocket(port);
            System.out.println("服务器已成功在" + port + "端口启动");
            System.out.println("等待客户端连接......");
            Socket socket = ss.accept();
            System.out.println("客户端已连接");

            String wel = "Welcome to the voivi's world";
            System.out.println("准备欢迎中~");

            OutputStream out = socket.getOutputStream();//套接字获取输出流
            PrintWriter pw = new PrintWriter(out);
            pw.println(wel);
            pw.flush();//刷新该流缓冲
            System.out.println("欢迎语已经发送");
            pw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ss != null)
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}

